import React from "react";
import "./pinlun.css"
import axios from "axios"
class Pinlun extends React.Component {
  state = {
    inputValue: "",
    textareaValue: "",
    pinlunList: [
      { id: 1, name: "fenglong", content: "你好" },
      { id: 2, name: "fenglong", content: "你好" },
      { id: 3, name: "fenglong", content: "你好" }
    ],
    data: ''
  };

  inputChange = e => {
    this.setState({ inputValue: e.target.value });
  };
  textareaChange = e => {
    this.setState({ textareaValue: e.target.value });
  };

  send = () => {
    let len =
      this.state.pinlunList.length === 0
        ? 1
        : this.state.pinlunList[this.state.pinlunList.length - 1].id + 1;

    if (this.state.inputValue.trim() === "" || this.state.textareaValue.trim() === "")
      return alert("请输入内容");

    this.setState({
      pinlunList: [
        {
          id: len,
          name: this.state.inputValue,
          content: this.state.textareaValue
        },
        ...this.state.pinlunList,
      ],
      inputValue: "",
      textareaValue: ""
    });
  };

  clear = () => {
    this.setState({
      inputValue: "",
      textareaValue: "",
      pinlunList: []
    });
  };

  // 生命周期函数
  componentDidMount() {
    console.log("组件已经被渲染到 DOM 中后运行(组件挂在完成时触发)", this.props.name);
    console.log("组件已经被渲染到 DOM 中后运行(组件挂在完成时触发)", this.props.getDatas('soasdfsadfn'));

    axios.get("http://localhost:3003/news").then(res => {
      console.log(res);
      this.setState({ pinlunList: res.data.reverse() })
    }).catch(err => {
      alert("json-server没有开启，使用默认数据", err)
      console.log(err, '错误数据');
    })
  }

  componentWillUnmount() {
    console.log("组件销毁时触发");
  }

  isShow = () => {
    if (this.state.pinlunList.length === 0) {
      return <p>暂无内容</p>;
    }
    return (
      <ul>
        {this.state.pinlunList.map(item => (
          <li key={item.id}>
            <label>评论人：</label>
            <span>{item.name}</span>
            <p>{item.content}</p>
          </li>
        ))}
      </ul>
    );
  };

  render() {
    return (
      <div id="pinlun">
        <div>
          <input
            placeholder="请输入评论人"
            type="text"
            value={this.state.inputValue}
            onChange={this.inputChange}
          ></input>
        </div>
        <div>
          <textarea
            placeholder="请输入评论内容"
            type="text"
            value={this.state.textareaValue}
            onChange={this.textareaChange}
          ></textarea>
        </div>
        <div>
          <button onClick={this.send}>发表评论</button>
          <button onClick={this.clear}>清空评论</button>
        </div>
        {this.isShow()}
      </div>
    );
  }
}

export default Pinlun;
